/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.equator.ging;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author Cerulean
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws FileNotFoundException, IOException {
        // TODO code application logic here

        // arguments check
        if(args.length!=3){
            System.out.println("Argument : [filename] [indexname] [outname]");
            return;
        }

        String filename=args[0];
        String indexfile=args[1];
        String outname=args[2];
        // build index
        ArrayList<String> index=new ArrayList<String>();
        BufferedReader br=new BufferedReader(new FileReader(indexfile));
        while(br.ready()){
            index.add(br.readLine());
        }
        br.close();
        // load guide
        StringBuilder guide=new StringBuilder();
        br=new BufferedReader(new FileReader(filename));
        String newline=System.getProperty("line.separator");
        while(br.ready()){
            guide.append(br.readLine()).append(newline);
        }
        br.close();
        // compile guide
        StringBuilder compiler=new StringBuilder();
        compiler.append("<html>").append(newline);
        compiler.append("\t<head>").append(newline);
        compiler.append("\t</head>").append(newline);
        compiler.append("\t<body id=\"top\">").append(newline);
        compiler.append("\t\t<pre>").append(newline);
        String guideString=guide.toString();
            // add tag
        for(String indices:index){
            Pattern p=Pattern.compile(indices);
            Matcher m=p.matcher(guideString);
            StringBuffer sb=new StringBuffer();
            if(m.find()){
                m.appendReplacement(sb, "<a href=\"#"+indices+"\">"+indices+"</a>");
            }
            if(m.find()){
                m.appendReplacement(sb, "<a href=\"#top\"><label id=\""+indices+"\">"+indices+"</label></a>");
            }
            m.appendTail(sb);
            guideString=sb.toString();
        }
            // add string into compiler
        compiler.append(guideString);
        compiler.append("\t</pre>").append(newline);
        compiler.append("\t</body>").append(newline);
        compiler.append("</html>");
        // finish
        String compiled=compiler.toString();
        // save file
        BufferedWriter bw=new BufferedWriter(new FileWriter(outname));
        bw.write(compiled);
        bw.close();
    }
}